<template>
  <div class="mqtt">
  </div>
</template>

<script>

import mqtt from "mqtt";
import MavLink20Processor from "../utils/mavlink20_processor";
import CmdTtsText from "../utils/cmd_tts_text";
import CmdReadFileList from "../utils/cmd_read_file_list";
import CmdRecordName from "../utils/cmd_record_name";
import CmdSetSystemVolume from "../utils/cmd_set_system_volume";
import CmdStreamUpData from "../utils/cmd_stream_up_data";

export default {
  data () {
    return {
      mqtt: {
        client: null,
        encoder: new TextEncoder(),
      }
    };
  },
  methods: {
    mqtt_publish (message, cmd) {
      this.mqtt.client.publish("SPEAK/OBTAIN/PoliceF737-01", message, { qos: 0 },
        (e) => {
          console.log("发送【" + cmd + "】指令成功:", message);
        }
      );
    },

    handleSendTTSText () {
      let cmdTTSText = new CmdTtsText(
        this.mqtt.encoder.encode(this.tts.text),
        "<B250A"
      );
      let message = cmdTTSText.pack();
      message = Uint8Array.from(message);
      this.mqtt_publish(message);
    },

    handleGetMusicList () {
      let cmdReadFileList = new CmdReadFileList();
      let message = cmdReadFileList.pack();
      message = Uint8Array.from(message);
      this.mqtt_publish(message);
    },

    handlePlayMusic (data) {
      let cmd = new CmdRecordName(
        this.mqtt.encoder.encode(data.name),
        "<B100A"
      );

      let message = cmd.pack();
      message = Uint8Array.from(message);

      this.mqtt_publish(message);
    },

    handleChangeVolume (cate) {
      this.setting.volume = this.setting.volume + cate;
      let cmd = new CmdSetSystemVolume(this.setting.volume);
      let message = cmd.pack();
      message = Uint8Array.from(message);

      this.mqtt_publish(message);
    },

    handleSendStreamUpData (blob) {
      blob = new Blob(blob, { type: "audio/mpeg; codecs=opus" });

      let fr = new FileReader();
      fr.onload = () => {
        let u8 = new Uint8Array(fr.result);
        console.log("u8:", u8);
        // let cmd = new CmdStreamUpData(u8.length, u8);
        // let message = cmd.pack();
        // message = Uint8Array.from(message);
        // this.mqtt_publish(message);
      };
      fr.readAsArrayBuffer(blob);
    },

    async blob2arraybuffer (blob) {
      if (!blob) {
        return Promise.reject(blob);
      }
      return new Promise((resolve, reject) => {
        let fileReader = new FileReader();
        fileReader.onload = () => resolve(fileReader.result);
        fileReader.onerror = (e) => reject(e);
        fileReader.readAsArrayBuffer(blob);
      });
    },

    async shout_producer () {
      try {
        let blob = this.shout.chunks.shift()
        console.log("blob:", blob);
        let arrayBuffer = await this.blob2arraybuffer(blob);
        this.shout.buffer.push(...new Uint8Array(arrayBuffer));
        setTimeout(() => {
          this.shout_producer();
          console.log("shout_producer");
        }, 1000);
      } catch (e) {
        console.error(e);
      }
    },

    shout_consumer () { },

    async handleStartShout () {
      async function getDeviceId () {
        return new Promise((resolve, reject) => {
          navigator.mediaDevices
            .enumerateDevices()
            .then((devices) => {
              resolve(
                devices.find((deviceInfo) => deviceInfo.kind === "audioinput")
              );
            })
            .catch((e) => reject(e));
        });
      }

      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        const deviceId = await getDeviceId();

        if (!deviceId) return;

        const contraints = {
          audio: {
            deviceId,
            sampleRate: 44100,
            sampleSize: 16,
          },
        };

        navigator.mediaDevices.getUserMedia(contraints).then((stream) => {
          const options = { mimeType: "audio/webm" };
          const recorder = new MediaRecorder(stream, options);
          let isStartShut = false;

          recorder.ondataavailable = (e) => {
            this.shout.chunks.push(e.data);

            if (!isStartShut) {
              this.shout_producer();
              isStartShut = true;
            }
          };

          recorder.start(800);

          recorder.onstop = (e) => {
            console.log("this.shut:", this.shout);
          };
          // recorder.onstop = (e) => {
          //   // var audio = document.createElement("audio");
          //   // audio.controls = true;
          //   // document.body.appendChild(audio);
          //   var blob = new Blob(chunks, { type: "audio/mpeg; codecs=opus" });

          //   let fr = new FileReader();
          //   fr.onload = () => {
          //     let u8 = new Uint8Array(fr.result);
          //     let cmd = new CmdStreamUpData(u8.length, u8);
          //     let message = cmd.pack();
          //     message = Uint8Array.from(message);
          //     this.mqtt_publish(message);
          //   };
          //   fr.readAsArrayBuffer(blob);

          //   // var audioURL = window.URL.createObjectURL(blob);
          //   // audio.src = audioURL;
          // };

          // setTimeout(() => {
          //   recorder.stop();
          //   console.log("recorder.stop");
          // }, 2000);
        });
      }

      return false;
      console.log("handleStartShout:");
      CmdStreamUpData.getUserMedia(
        { video: false, audio: true },
        (stream) => {
          stream.getTracks().forEach(function (track) {
            console.log(track);
          });

          // this.shout.stream = stream;
          // console.log("stream:", stream);

          // var mediaRecorder = new MediaRecorder(stream);
          // console.log("aaa stream:", mediaRecorder);

          // let audio = document.createElement("audio");
          // audio.srcObject = stream;

          // let recorder = RecordRTC(stream, {
          //   type: "audio",
          //   mimeType: "video/webm",
          // });

          // recorder.startRecording();

          // setTimeout(() => {
          //   //recorder.stopRecording(function () {
          //     let blob = recorder.getBlob();
          //     console.log("redorder:", blob);
          //   //});
          // }, 5000);
        },
        (error) => console.error(error)
      );
    },

    handleStartShoutDown () {
      console.log("handleStartShoutDown:");
      let stream = this.shout.stream;
      if (stream) {
        stream.getTracks().forEach(function (track) {
          track.stop();
        });
      }
    },
  },
  mounted () {
    // let url = "mqtt://192.168.230.69:8883/mqtt";    // 汪雄
    let url = "mqtt://200.10.1.88:8883/mqtt";   // 专网
    // let url = "mqtt://200.10.1.245:8883/mqtt";   // 汪雄2
    // let url = "mqtt://192.168.230.217:8883/mqtt";
    let uid = crypto.randomUUID()
    // 创建mqtt
    this.mqtt.client = mqtt.connect(url, { protocol: "mqtt", clientId: uid });
    console.log('创建mq链接', uid);

    // 订阅主题
    this.mqtt.client.subscribe(`SPEAK/PUBLISH/PoliceF737-01`, (e) => {
      console.log('订阅主题', e);
      console.log("subscribe on_and_off_broker");
    });

    let music_list = [];
    this.mqtt.client.on("message", (topic, payload, packet) => {
      console.log("paryload:", topic, payload, packet);
      music_list = [];
      let parser = new MavLink20Processor();
      let buffers = parser.parseBuffer(Uint8Array.from(payload));

      buffers.forEach((item) => {
        if (item.header && item.header.msgId === 100100) {
          let name = new TextDecoder().decode(item.name);
          name = name.replace(/\x00/g, "");
          let music = music_list.find((i) => i.id === item.id);
          if (!music) {
            music_list.push({
              ...item,
              name,
            });
          }
        }
      });

      if (music_list && music_list.length) {
        console.log("music_list:", music_list);
        this.music.list = music_list;
      }
    });
  },
};
</script>

<style lang="scss" scoped>
* {
  box-sizing: border-box;
}
fieldset {
  width: 500px;
  margin: 0;
  padding: 8px;
  border-width: 1px;
  .content {
    .input__box,
    .music-list {
      width: 100%;
      height: 140px;
      overflow: auto;
      border: 1px solid black;
      textarea {
        display: block;
        padding: 0;
        margin: 0;
        width: 100%;
        height: 100%;
        border: 0px;
        resize: none;
        outline: none;
        padding: 6px 8px;
      }
    }
    .music-list {
      .music__item {
        font-size: 12px;
        padding: 4px 6px;
        &:nth-child(odd) {
          background-color: #ececec;
        }
        button {
          margin-right: 4px;
        }
      }
    }
  }
}
</style>